var Mock = require('mockjs');
const RespEncode = require('../util/RespEncode')


const toJson = (data) => JSON.stringify(data, null, 4);

function timeout(ms) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, ms, 'done');
    });
}

const randomBool = () => {
    return 0 === Mock.Random.integer(0, 9) % 2;
}

const readomPhone = () => {
    const value = Mock.mock({
        'regexp': /1[358]{1}[0-9]{9}/
    });

    return value.regexp;
}

const readomRoles = () => {
    // var data2 = Mock.mock({
    //     'name3|1':true, //"1"为数字，没有意义，必须存在，随机显示true或false
    //     'name4|1-9':true//出现true的概率为1/（1+9），false的概率为9/（1+9）
    // })

    const value = Mock.mock({
        "user|1-0": true,
        "admin|1-3": true,
        "test|1-3": true
    });

    const roles = Object.keys(value).reduce((prov, key) => {
        if (true === value[key]) {
            prov.push(key);
        }
        return prov;
    }, []);

    return roles;
}



async function getUserList() {

    await timeout(1000);

    const list = Mock.mock({
        "array|1-200": [
            {
                'username': Mock.mock('@string(7, 10)'),
                'email': Mock.mock('@email'),
                'phone': () => randomBool() ? null : readomPhone(),
                'state': Mock.Random.integer(0, 2),
                'roles': readomRoles,
            }
        ]
    });

    return list.array;
}

module.exports = {toJson, getUserList};
